package com.heihei.common.tree;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *  构建树
 *
 * @version 1.0
 * @since JDK1.8
 * @author duanhengfei
 * @date 2021年02月24日 10:25:54
 */
public class ForestNodeManager<T extends INode<T>> {
    private final ImmutableMap<Long, T> nodeMap;
    private final Map<Long, Object> parentIdMap = Maps.newHashMap();

    public ForestNodeManager(List<T> nodes) {
        this.nodeMap = Maps.uniqueIndex(nodes, INode::getId);
    }

    public INode<T> getTreeNodeAt(Serializable id) {
        return this.nodeMap.containsKey(id) ? (INode)this.nodeMap.get(id) : null;
    }

    public void addParentId(Long parentId) {
        this.parentIdMap.put(parentId, "");
    }

    public List<T> getRoot() {
        List<T> roots = new ArrayList();
        this.nodeMap.forEach((key, node) -> {
            if (RootPredicates.isRoot(key) || this.parentIdMap.containsKey(node.getId())) {
                roots.add(node);
            }

        });
        return roots;
    }
}
